<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <th:block th:include="include :: device-css"/>
    <link href="/ajax/libs/ol-6.9.0/ol.css" rel="stylesheet"/>
    <link href='/ajax/libs/sm-11.1.0/iclient-ol.min.css' rel='stylesheet'/>
    <style>
        .ol-popup {
            position: absolute;
            background: rgba(12, 16, 35, 0.45);
            text-shadow: rgba(0, 0, 0, 0.7) 1px 2px 2px;
            color: #ffffff;
            -webkit-filter: drop-shadow(0 1px 4px rgba(0, 0, 0, 0.2));
            filter: drop-shadow(0 1px 4px rgba(0, 0, 0, 0.2));
            padding: 15px;
            border-radius: 10px;
            border: 1px solid #cccccc;
            bottom: 12px;
            left: -150px;
            min-width: 150px;
        }

        .ol-popup:after, .ol-popup:before {
            top: 100%;
            border: solid transparent;
            content: " ";
            height: 0;
            width: 0;
            position: absolute;
            pointer-events: none;
        }

        .ol-popup:after {
            border-top-color: rgba(0, 0, 0, 0.2);
            border-width: 10px;
            left: 48px;
            margin-left: -10px;
        }

        .ol-popup:before {
            border-top-color: rgba(0, 0, 0, 0.2);
            border-width: 11px;
            left: 48px;
            margin-left: -11px;
        }

        .ol-popup-func {
            position: absolute;
            top: 0;
            right: 10px;
            padding: 0 10px;
        }
        .ol-attribution, .ol-control-logo {
            display: none;
        }
    </style>
</head>
<body>
<div class="wrapper">

    <div class="row chart-title"></div>
    <div class="row">
        <div class="col-sm-12">
            <div id="map" style="width: 100%;background-color: #000000"></div>
        </div>
    </div>
    <div class="row search-row" id="toolbar">
        <div class="col-sm-12">
            <form id="formId">
                <button type="button" class="btn btn-primary btn-rounded btn-sm"
                        id="view-btn" onclick="scrollToTable()">
                    <i class="fa fa-list"></i>
                </button>
                <input type="text" class="date-input" placeholder="日期" id="date"
                       style="width: 180px; text-align: center; padding-left: 0"
                       name="date" autocomplete="off">
                <input type="hidden" id="beginTime" name="params[beginTime]">
                <input type="hidden" id="endTime" name="params[endTime]">
                <input type="hidden" th:value="${boat.code}" name="boatCode">
                <button type="button" class="btn btn-primary btn-rounded btn-sm" onclick="search()">
                    <i class="fa fa-search"></i>
                </button>
                <button type="button" class="btn btn-warning btn-rounded btn-sm" onclick="resetInput()">
                    <i class="fa fa-refresh"></i>
                </button>
                <button type="button" class="btn btn-success btn-rounded btn-sm" id="download-btn"
                        onclick="openDownloadDialog()">
                    <i class="fa fa-cloud-download"></i>
                </button>
            </form>
        </div>
    </div>
    <div class="col-sm-12" id="table-row">
        <table id="bootstrap-table"></table>
    </div>
</div>

<div id="popup" class="ol-popup">
    <div id="popup-content">
        <div>mmsi : <span class="mmsi">-</span></div>
        <div>经度 ：<span class="lng">-</span></div>
        <div>纬度 ：<span class="lat">-</span></div>
        <div>航向 ：<span class="direction">-</span></div>
        <div>速度 ：<span class="speed">-</span></div>
    </div>
</div>

<div id="popup-func" class="ol-popup-func">
    <div class="btn-group" role="group" aria-label="...">
        <button id="measure" value='Measure' type="button" class="btn btn-default">测距</button>
        <button id="clear" value='Clear' type="button" class="btn btn-default">清除</button>
        <button id="see-map" value='SeeMap' type="button" class="btn btn-default see-map-show">海图</button>
    </div>
</div>

<th:block th:include="include :: device-js"/>
<script th:inline="javascript">
    var mapHost = [[${mapHost}]];
</script>
<script type="text/javascript" src="/ajax/libs/ol-6.9.0/ol.js"></script>
<script type="text/javascript" src="/ajax/libs/sm-11.1.0/iclient-ol.min.js"></script>
<script type="text/javascript" src="/js/map/data.js"></script>
<script type="text/javascript" src="/js/map/map-util.js"></script>
<script type="text/javascript" src="/js/map/map.js"></script>
<script th:inline="javascript">
    var msgType = 'aisData';
    var boatCode = [[${boat.code}]];
    let downloadUrl = '/boat/aisData/export';
    windowResizeCallback(); // 先设置地图高度
    initMap();

    function msgGot(object) {
        if (object.type !== msgType || object.data.boatCode !== boatCode) return;

        let data = object.data;
        let label = data.time;
    }

    var prefix = "/boat/aisData";
    var options = {
        url: prefix + "/list",
        createUrl: prefix + "/add",
        updateUrl: prefix + "/edit/{id}",
        removeUrl: prefix + "/remove",
        exportUrl: prefix + "/export",
        modalName: "测风雷达",
        showSearch: false,
        showRefresh: false,
        showColumns: false,
        showToggle: false,
        clickToSelect: true,
        singleSelect: true,
        sortName: 'id',
        sortOrder: 'desc',
        sidePagination: 'server',
        onLoadSuccess: function (data) {
            dataList = data.rows;
            if ($.common.isEmpty(dataList)) dataList = [];
            if (dataList.length === 0) {
                $.modal.msg(currentDate + ' 无数据')
            }
            try {
                prepareData(); // 这里 把通用的clearData 和 initChart全部放进这里
            } catch (e) {
                console.log(e)
            }
        },
        onClickCell: function (field, value, row, $element) {
            showMap(row)
        },
        columns: [
            {
                checkbox: true
            },
            {
                field: 'time',
                title: '数据时间'
            },
            {
                field: 'lng',
                title: '艇经度'
            },
            {
                field: 'lat',
                title: '艇纬度'
            },
            {
                field: 'count',
                title: '船舶数量'
            },
        ]
    };
    $.table.init(options);


    var aisContent;
    var aisContentOverlay;

    /**
     * 初始化
     * map变量已在最前面声明
     */
    function initMap() {
        //加载地图
        loadMap(sourceUrlList, bounds).then(map => {
            boatPointSource = new ol.source.Vector({
                wrapX: false
            });
            this.map = map;
            // resolution 变更
            map.getView().on('change:resolution', resolutionChangeListener)
            // 鼠标悬浮在一个AIS点位上,弹窗显示
            var container = document.getElementById('popup');
            aisContent = document.getElementById('popup-content');
            aisContentOverlay = new ol.Overlay(({
                element: container,
                autoPan: true,
                autoPanAnimation: {
                    duration: 250
                },
                offset: [0, -20]
            }))
            map.on('pointermove', aisMoveListener);
            map.on('movestart',aisMapMoveStartListener);
            map.on('moveend',aisMapMoveEndListener);
        })
    }

    function aisMapMoveStartListener(e){
        mapMove = true;
        map.getTargetElement().style.cursor = '';
        aisContentOverlay.setPosition(undefined);
        map.removeOverlay(aisContentOverlay);
    }

    function aisMapMoveEndListener(e){
        mapMove = false;
    }

    function aisMoveListener(e) {
        var select = false;
        map.forEachFeatureAtPixel(e.pixel, function (feature) {
            var prop = feature.getProperties();
            if (prop.type === featureType.AIS && !mapMove) {
                map.getTargetElement().style.cursor = 'pointer';
                $("#popup-content .mmsi").html(prop.mmsi);
                $("#popup-content .lng").html(prop.lng);
                $("#popup-content .lat").html(prop.lat);
                $("#popup-content .direction").html(prop.direction);
                $("#popup-content .speed").html(prop.speed);

                var offset = [100, 0]; // X偏移量为100像素，Y偏移量为0像素
                // 获取当前 feature 的像素坐标
                var pixelCoordinates = map.getPixelFromCoordinate(feature.getGeometry().getCoordinates());
                // 计算偏移后的像素坐标
                var offsetPixelCoordinates = [pixelCoordinates[0] + offset[0], pixelCoordinates[1] + offset[1]];
                // 将像素坐标转换为地理坐标
                var offsetCoordinates = map.getCoordinateFromPixel(offsetPixelCoordinates);
                // 设置弹出式覆盖层的位置
                aisContentOverlay.setPosition(offsetCoordinates);
                map.addOverlay(aisContentOverlay);
                select = true
            }
        }, {
            hitTolerance: 10
        });
        if (!select) {
            map.getTargetElement().style.cursor = '';
            aisContentOverlay.setPosition(undefined);
            map.removeOverlay(aisContentOverlay);
        }
    }

    /**
     * 根据一条ais消息在地图中画出艇和其他船
     * @param data
     */
    function showMap(data) {
        // 显示时间标题
        $('.chart-title').html(data.time)
        // 清楚地图现有marker
        cleanAisFeature(boatPointSource, map);
        // 如果这条ais数据没有其他船只就返回
        if (data.count === 0) return;
        var pointList = [];
        pointList[0] = {
            lng: data.lng,
            lat: data.lat,
            boatCode: data.boatCode,
            type: featureType.boat
        }
        for (let i = 1; i < 5; i++) {
            pointList[i] = {};
        }
        data.mmsiList.split(',').forEach(function (item, index) {
            pointList[index + 1].mmsi = item;
            pointList[index + 1].type = featureType.AIS;
        })
        data.lngList.split(',').forEach(function (item, index) {
            pointList[index + 1].lng = item;
        })
        data.latList.split(',').forEach(function (item, index) {
            pointList[index + 1].lat = item;
        })
        data.directionList.split(',').forEach(function (item, index) {
            pointList[index + 1].direction = item;
        })
        data.speedList.split(',').forEach(function (item, index) {
            pointList[index + 1].speed = item;
        })

        // 显示ais船舶和艇 鼠标悬浮显示mmsi 经纬度 航速航向 艇的 是编号 经纬度 图标是波浪艇图标吧 没有图标前 先画个圆
        showAisFeature(boatPointSource, map, pointList);
        // 地图居中
        mapPanByLocationWithoutZoomChange(data.lng, data.lat);
    }

    function prepareData() {
        if (dataList.length === 0) return;
        showMap(dataList[0])
    }

    /**
     * 在window resize的时候被调用 在这里根据map父元素的宽度去调整map高度
     */
    function windowResizeCallback() {
        $('#map').height($('#map').width() * 2 / 4)
    }
</script>

</body>
</html>